import React, { useEffect, useState } from 'react';
import { Cascader } from '@arco-design/web-react';
import {
  getAllDicApi,
  getKnowledgeAllApi,
  getLessonAllApi,
  getSectionAllApi,
} from '@/request/api';

const DictionaryModal = ({ info, selectChange, defaultValue }) => {
  const [value, setValue] = useState([]);
  const [options, setOptions] = useState([
    {
      key: 0,
      value: '课程',
      children: [],
    },
    {
      key: 1,
      value: '章节',
      children: [],
    },
    {
      key: 2,
      value: '一级知识节点',
      children: [],
    },
    {
      key: 3,
      value: '二级知识节点',
      children: [],
    },
  ]);

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    setValue(defaultValue);
  }, [defaultValue]);

  const fetchData = () => {
    // 一级知识
    getKnowledgeAllApi({ schCourseId: info.schCourseId, type: 0 })
      .then((res) => {
        const { data } = res;
        console.log(info, data, 'getKnowledgeAllApi0');
        options[2].children = data;
        setOptions([...options]);
      })
      .catch((e) => {
        console.log(e);
      });

    // 二级知识
    getKnowledgeAllApi({ schCourseId: info.schCourseId, type: 1 })
      .then((res) => {
        const { data } = res;
        console.log(info, data, 'getKnowledgeAllApi1');
        options[3].children = data;
        setOptions([...options]);
      })
      .catch((e) => {
        console.log(e);
      });

    // 课程
    getLessonAllApi({})
      .then((res) => {
        const { data } = res;
        options[0].children = data;
        setOptions([...options]);
      })
      .catch((e) => {
        console.log(e);
      });

    // 章节
    getSectionAllApi({})
      .then((res) => {
        const { data } = res;
        options[1].children = data;
        setOptions([...options]);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const onChange = (value, option) => {
    setValue(value);
    console.log(value);
    const ids = value.map((id) => {
      return {
        refBizType: id[0],
        refBizId: id[1],
      };
    });
    selectChange(ids);
  };

  return (
    <div>
      <Cascader
        placeholder="请添加"
        style={{ width: 300 }}
        options={options}
        mode="multiple"
        value={value}
        fieldNames={{
          children: 'children',
          label: 'value',
          value: 'key',
        }}
        onChange={(value, option) => onChange(value, option)}
      />
    </div>
  );
};

export default DictionaryModal;
